<template>
    <el-table :data="tableData" border @selection-change="handleSelectionChange" show-summary
              :summary-method="getSummaries">
        <slot></slot>
    </el-table>
</template>

<script>
export default {
    name: 'ReusableTable',
    props: {
        tableData: {
            type: Array,
            required: true
        },
        indexValue: {
            type: Number,
            default: 0
        }
    },
    methods: {
        handleSelectionChange(val) {
            this.$emit('manyChange', val)
        },
        // 表格合计
        getSummaries(param) {
            const {columns, data} = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计:'
                    //只计算最后一列
                } else if (index === this.indexValue) {
                    const values = data.map(item => Number(item[column.property]))
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr)
                            if (!isNaN(value)) {
                                return prev + curr
                            } else {
                                return prev
                            }
                        }, 0)
                        sums[index] += ' 元';
                    } else {
                        sums[index] = '';
                    }
                } else {
                    sums[index] = ''
                }
            })
            return sums
        }
    }
}
</script>

<style scoped>
::v-deep .el-table__footer-wrapper .cell {
    font-weight: 600;
    color: #000;
}
</style>